#include "StdAfx.h"
#include "FreeRayReq.h"


FreeRayReq::FreeRayReq(Ogre::RaySceneQuery* rayScnQuery,Ogre::Vector3 s, Ogre::Vector3 d, int dist)
{
	this->mRayScnQuery = rayScnQuery;
	this->startPos = s;
	this->dir = d;
	this->distance = dist;

}


FreeRayReq::~FreeRayReq(void)
{
}

bool FreeRayReq::CheckReq(EntityControl *entity)
{

	Ogre::Vector3 entityPos = ((VectorEntityParameter*)entity->getParameter(POSITION_PARAMETER))->getVectorValue();
	Ogre::Vector3 entityDir = ((VectorEntityParameter*)entity->getParameter(LOOKAT_PARAMETER))->getVectorValue();

	Ogre::Quaternion rotation = Ogre::Vector3::UNIT_X.getRotationTo(entityDir);



	Ogre::Ray checkRay(entityPos+startPos,rotation*dir);
	mRayScnQuery->setRay(checkRay);
	mRayScnQuery->setSortByDistance(true);
	Ogre::RaySceneQueryResult& result = mRayScnQuery->execute();



	Ogre::RaySceneQueryResult::iterator iter = result.begin();
	if(iter!= result.end() && iter->distance <= distance  )
	{
		for(iter; iter != result.end(); iter++)
		{
			if(iter->movable->getName()!=entity->getName() && iter->movable->getName()!="mainCam" && iter->distance <= distance )
			{

				Ogre::Vector3 targetPos = iter->movable->getParentSceneNode()->getPosition();
				VectorEntityParameter * targetParam = new VectorEntityParameter("target",targetPos); 
				entity->setParameter("target", targetParam);

				Ogre::Vector3 boxSize = iter->movable->getBoundingBox().getSize();
				Ogre::Vector3 dist = targetPos-entity->getPosition();
				if(abs(dist.x)<boxSize.x*0.5 && abs(dist.y)<boxSize.y*0.5 && abs(dist.z)<boxSize.z*0.5)
				{
					return false;
				}

				
			}
		}
	}


	return true;



}

void FreeRayReq::subscribeParameterChanged(EntityControl *entity,TriggerRequirement*req)
{
	entity->subscribeForParameter(POSITION_PARAMETER, req);
}

void FreeRayReq::unSubscribeParameterChanged(EntityControl *entity,TriggerRequirement*req)
{
	entity->unSubscribeForParameter(POSITION_PARAMETER, req);
}
